package teacher;


import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.*;

// 2.根据评分数据得到每位用户的评分前三名（输出格式：用户编号,评分）
public class Score2 {

    public static class Score2Mapper extends Mapper<LongWritable, Text, IntWritable, Text> {

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            //读取数据
            String line = value.toString();
            //进行处理
            String[] split = line.split("::");
            int userId = Integer.parseInt(split[0]);
            String movieInfo = split[1] + "," + split[2];
            context.write(new IntWritable(userId), new Text(movieInfo));
        }
    }

    public static class Score2Reducer extends Reducer<IntWritable, Text, IntWritable, Text> {

        @Override
        protected void reduce(IntWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            Map<Integer, Integer> map = new HashMap<>();
            int sum = 0;
            for (Text value : values) {
                String[] split = value.toString().split(",");
                int movieId = Integer.parseInt(split[0]);
                int rating = Integer.parseInt(split[1]);
                map.put(movieId, rating);
            }

            Set<Map.Entry<Integer, Integer>> entrySet = map.entrySet();
            ArrayList<Map.Entry<Integer, Integer>> list = new ArrayList<>(entrySet);
            Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
                @Override
                public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                    return o2.getValue().compareTo(o1.getValue()); // 降序排序
                }
            });

            for (int i = 0; i < Math.min(list.size(), 3); i++) {
                context.write(key, new Text(list.get(i).getKey() + "," + list.get(i).getValue()));
            }
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        Configuration config = new Configuration();
        Job job = Job.getInstance(config);
        job.setJarByClass(Score2.class);
        job.setMapperClass(Score2Mapper.class);
        job.setReducerClass(Score2Reducer.class);
        job.setMapOutputKeyClass(IntWritable.class);
        job.setMapOutputValueClass(Text.class);
        job.setOutputKeyClass(IntWritable.class);
        job.setOutputValueClass(Text.class);

        FileSystem fs = FileSystem.get(config);
        Path inputPath = new Path(Config.RATE_PATH);
        Path outputPath = new Path(Config.OUT_PATH[2]);

        if (fs.exists(outputPath)) {
            fs.delete(outputPath, true);
        }

        FileInputFormat.setInputPaths(job, inputPath);
        FileOutputFormat.setOutputPath(job, outputPath);
        boolean isDone = job.waitForCompletion(true);
        System.out.println(isDone ? "执行成功" : "执行失败");
    }
}